package com.oa.works.config.shiro;

import com.oa.works.pojo.TbUser;
import com.oa.works.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 用户授权与认证
 * @date 2021/10/13 17:41
 * @author Qin
 */
@Component
public class OAuth2Realm extends AuthorizingRealm  {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token){
        //instanceof 判断左右两边的对象是否是同一类的实例
        return token instanceof OAuth2Token;
    }

    /**
     * 授权（验证权限时调用）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection){
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        TbUser user = (TbUser) principalCollection.getPrimaryPrincipal();
        int usedId = user.getId();
        Set<String> permsSet = userService.searchUserPermissions(usedId);
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证（验证登录时调用）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String)token.getPrincipal();
        int userId = jwtUtil.getUserId(accessToken);
        TbUser user = userService.searchById(userId);
        if (user == null){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,accessToken,getName());
        return info;
    }

}



